package com.kll.tv.views.adapter

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.kll.carolinehmibiz.net.bean.GetAddressResponse
import com.kll.tv.R
import com.kll.tv.databinding.ItemMyAddressBinding

class MyHarvestAddressAdapter(var context: Context): RecyclerView.Adapter<MyHarvestAddressAdapter.InnerHolder>() {

    private var mItemClickListener: OnAddressListItemClickListener? = null

    // 数据
    var data: MutableList<GetAddressResponse> = ArrayList()
        set(value) {
            if (value == null) {
                data.clear()
            } else {
                field = value
            }
            notifyDataSetChanged()
        }

    fun addData(data: ArrayList<GetAddressResponse>) {
        if (data != null) {
            this.data.addAll(data)
            notifyDataSetChanged()
        }
    }

    inner class InnerHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        var binding = ItemMyAddressBinding.bind(itemView)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): InnerHolder {
        val view = LayoutInflater.from(context).inflate(R.layout.item_my_address, parent, false)
        return InnerHolder(view)
    }

    override fun onBindViewHolder(holder: InnerHolder, position: Int) {
        val data = data[position]

        // item可以获得焦点，需要设置这个属性。
        holder.itemView.setFocusable(true)
        holder.itemView.nextFocusLeftId = R.id.tv_contact_family
        holder.itemView.setBackgroundResource(R.drawable.bg_text_btn)
        if (position == this.data.size) {
            holder.itemView.nextFocusDownId = 0
        }

        holder.binding.tvName.text = data.consignee
        holder.binding.tvAddress.text = data.region + "   " + data.address
        holder.binding.tvPhone.text = data.mobile
        holder.binding.tvDefault.visibility = if (data.is_default == 0) View.GONE else View.VISIBLE

        if (mItemClickListener != null) {
            holder.itemView.setOnClickListener {
                mItemClickListener!!.onAddressItemClick(data)
            }
        }
    }

    override fun getItemCount(): Int {
        return data.size
    }

    interface OnAddressListItemClickListener {
        fun onAddressItemClick(data: GetAddressResponse)
    }

    fun setOnAddressListItemClickListener(listener: OnAddressListItemClickListener) {
        this.mItemClickListener = listener
    }

}